import router from './router'
import { useUserStore } from './store/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/get-page-title'
import { getCookieByKey } from '@/utils/cookies'
import settings from "@/settings.js";

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)

  const hasToken = getCookieByKey(`${settings.cookiePrefix}token`)
  const user = useUserStore()
  if (hasToken && hasToken !== 'undefined') {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasRoles = user.roles && user.rolesLength > 0
      if (hasRoles) {
        next()
      } else {
        try {
          await user.loginByToken({})
          next({ ...to, replace: true })
        } catch (error) {
          await user.resetInfo()
          next(`/login`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
